package com.example.common.recycler.databinding;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.example.common.recycler.base.BaseBindView;
import com.example.common.recycler.base.BindViewStore;
import com.example.common.recycler.base.IBIndViewManager;

import java.util.List;

public class DataBindingBindViewManager<T, VDB extends ViewDataBinding> implements IBIndViewManager<T, DataBindingViewHolder<VDB>, BaseDataBindingBindView<T, VDB>> {
    private BindViewStore<BaseDataBindingBindView<T, VDB>> bindViewStore = new BindViewStore<>();

    @Override
    public DataBindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, viewType, parent, false);
        return new DataBindingViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull DataBindingViewHolder<VDB> holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        int type = getHashCode(t);
        bindViewStore.getBindView(type).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull DataBindingViewHolder<VDB> holder, @NonNull T t) {
        int code = getHashCode(t);
        BaseBindView bindView = bindViewStore.getBindView(code);
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseDataBindingBindView bindView) {
        bindViewStore.putBindView(bindView.itemBeanType.hashCode(), bindView);
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int type = t.getClass().hashCode();
        int resId = bindViewStore.getBindView(type).getItemLayoutResId(t);
        return resId;
    }

    private int getHashCode(@NonNull T t) {
        return t.getClass().hashCode();
    }

}
